package com.ruoyi.common.utils;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 安全服务工具类
 * 
 * @author ruoyi
 */
@Slf4j
public class SecurityUtils
{
    public static final String TENANT_ID = "tenant";
    public static final String TOKEN = "token";
    private static ThreadLocal<Long> threadLocal = new ThreadLocal<Long>();

    /**
     * 获取用户账户
     **/
    public static String getUsername()
    {
        try
        {
            return getLoginUser().getUsername();
        }
        catch (Exception e)
        {
            throw new CustomException("获取用户账户异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取用户
     **/
    public static LoginUser getLoginUser()
    {
        try
        {
            return (LoginUser) getAuthentication().getPrincipal();
        }
        catch (Exception e)
        {
            throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication()
    {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode(password);
    }

    /**
     * 判断密码是否相同
     *
     * @param rawPassword 真实密码
     * @param encodedPassword 加密后字符
     * @return 结果
     */
    public static boolean matchesPassword(String rawPassword, String encodedPassword)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    /**
     * 是否为管理员
     * 
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(Long userId)
    {
        return userId != null && 1L == userId;
    }

    /**
     * 获取用户
     **/
    public static SysUser getSysUser()
    {
        try
        {
            return getLoginUser().getUser();
        }
        catch (Exception e)
        {
            throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
        }
    }
    /**
     * 获取用户账户
     **/
    public static Long getTenantId()
    {
        try
        {
            return getLoginUser().getUser().getTenantId();
        }
        catch (Exception e)
        {
            throw new CustomException("获取用户租户Id异常", HttpStatus.UNAUTHORIZED);
        }
    }

    /**
     * 向ThreadLocal添加租户id
     *
     * @return 租户id
     */
    public static Long getThreadTenantId() {
        Long tenantId = null;
        try {
            if (tenantId == null) {
                tenantId = threadLocal.get();
                if (tenantId != null) {
                    log.debug("getThreadTenantId from threadLocal,tenantId={}", tenantId);
                    return tenantId;
                }
            }
            if (SecurityUtils.getTenantId() != null) {
                tenantId = SecurityUtils.getTenantId();
                if (tenantId != null) {
                    log.debug("getThreadTenantId from sysUser,tenantId={}", tenantId);
                    return tenantId;
                }
            }
        } catch (Exception e) {
            // 忽略错误.
            //log.error(e.getMessage(),e);
            tenantId = 1L;
        }

        return tenantId;
    }

    /**
     * 从ThreadLocal获取租户id
     *
     * @param tenantId 租户id
     */
    public static void setThreadTenantId(Long tenantId) {
        log.debug("setThreadTenantId,tenantId={}", tenantId);
        threadLocal.set(tenantId);
    }

    /**
     * 从ThreadLocal清除租户id
     */
    public static void removeThreadTenantId() {
        log.debug("removeThreadTenantId,tenantId={}",threadLocal.get());
        threadLocal.remove();
    }
}
